﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStuctureStudy.Queues
{
    public class ArrayQueue2<T>
    {
        private readonly int _maxSize;
        private readonly T[] _items;
        private int _header = 0;
        private int _tail = -1;

        public ArrayQueue2(int size)
        {
            _maxSize = size + 1;
            _items = new T[_maxSize];
        }

        public void EnQueue(T item)
        {
            if (this.IsFull())
            {
                throw new InvalidOperationException("队列已满");
            }

            if (_tail == _maxSize - 1)
            {
                _tail = -1;
            }

            _items[++_tail] = item;
        }

        public T DeQueue()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            T item = _items[_header++];

            if (_header == _maxSize)
            {
                _header = 0;
            }

            return item;
        }

        public T Peek()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            return _items[_header];
        }

        public bool IsFull()
        {
            return
               (_header + _maxSize - 2 == _tail)
               ||
               (_tail + 2 == _header);
        }

        public bool IsEmpty()
        {
            return
               (_tail + 1 == _header)
               ||
               (_header == 0 && _tail == _maxSize - 1);
        }

        public int Size()
        {
            if (_tail >= _header)
            {
                return _tail - _header + 1;
            }
            else
            {
                return (_maxSize - _header) + (_tail + 1);
            }
        }
    }
}
